package com.vr.cloudpicture.manager.websocket.strategy.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import com.vr.cloudpicture.manager.websocket.handler.PictureEditBroadcast;
import com.vr.cloudpicture.manager.websocket.handler.PictureEditingStatusManager;
import com.vr.cloudpicture.manager.websocket.model.PictureEditRequestMessage;
import com.vr.cloudpicture.manager.websocket.model.PictureEditResponseMessage;
import com.vr.cloudpicture.manager.websocket.model.enums.PictureEditMessageTypeEnum;
import com.vr.cloudpicture.manager.websocket.strategy.PictureEditMessageStrategy;
import com.vr.cloudpicture.model.dto.user.UserLogin;
import com.vr.cloudpicture.model.vo.UserVO;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

/**
 * 退出图片编辑状态处理的策略
 *
 * @author hzh
 * @date 2025/05/28
 */
@Component
public class ExitEditMessageStrategy implements PictureEditMessageStrategy {
    @Override
    public void handle(PictureEditRequestMessage requestMessage, WebSocketSession session, UserLogin user, Long pictureId) throws Exception {
        // 拿到正在编辑的用户
        Long editingUser = PictureEditingStatusManager.getEditingUser(pictureId);
        // 当前登录的用户是否是正在编辑的用户，应为自己才能退出编辑状态
        if (ObjUtil.isNotEmpty(editingUser) && user.getId().equals(editingUser)) {
            PictureEditingStatusManager.removeEditingUser(pictureId);
            // 构建响应
            PictureEditResponseMessage responseMessage = new PictureEditResponseMessage();
            responseMessage.setType(PictureEditMessageTypeEnum.EXIT_EDIT.getValue());
            String message = String.format("%s退出编辑图片", user.getUserName());
            responseMessage.setMessage(message);
            responseMessage.setUser(BeanUtil.toBean(user, UserVO.class));
            // 广播通知给同一张图片的所有用户
            PictureEditBroadcast.broadcastToPicture(pictureId, responseMessage);
        }

    }
}
